﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Api.Common;
using AppManager.Model;
using AppManager.DomainModel;
using AppManager.IBLL;

namespace AppManager.Background
{
    public class AppController : BaseController
    {
        IAppService appService;
        IAppInfoService appInfoService;
        public AppController(IAppService appServ, IAppInfoService appInfoServ)
        {
            appService = appServ;
            appInfoService = appInfoServ;
        }
        // GET: App
        public ActionResult Create()
        {
            ViewBag.TableTitle = "應用添加";
            Th.PageHeaderCrumbs = new List<string> { "應用添加", "Home", "應用管理" };
            Th.PageHeaderMenus = new Dictionary<string, string> { { "應用列表", Url.Action("List") } };
            return View("Edit");
        }

        public ActionResult Edit(int? id)
        {
            ViewBag.TableTitle = "應用修改";
            Th.PageHeaderCrumbs = new List<string> { "應用修改", "Home", "應用管理" };
            Th.PageHeaderMenus = new Dictionary<string, string> { { "應用列表", Url.Action("List") } };

            if (id == null) return RedirectToAction("List");
            var app = appService.GetModel(s => s.Id == id.Value && s.CreateUserId == userId);
            if (app == null) return RedirectToAction("List");

            app.AppInfos = appInfoService.GetListNoTrack(s => s.AppId == app.Id);
            var androidAppInfo = app.AndroidInfo;
            var iosAppInfo = app.IosInfo;

            var model = new AppInfoModel();

            model.Id = app.Id;
            model.AppLogo = app.AppLogo;
            model.Identity = app.Identity;
            model.Name = app.Name;
            model.PassWord = app.PassWord;
            model.AndroidUrl = androidAppInfo.Url;
            model.IosUrl = iosAppInfo.Url;
            model.AndroidTestUrl = androidAppInfo.TestUrl;
            model.IosTestUrl = iosAppInfo.TestUrl;
            model.AndroidVersion = androidAppInfo.Version;
            model.IosVersion = iosAppInfo.Version;
            model.AndroidPushDate = androidAppInfo.PushDate;
            model.IosPushDate = iosAppInfo.PushDate;
            model.AndroidAppSize = androidAppInfo.Size;
            model.IosAppSize = iosAppInfo.Size;
            model.AndroidDescription = androidAppInfo.Description;
            model.IosDescription = iosAppInfo.Description;
            model.AndroidUpdatedExplain = androidAppInfo.UpdatedExplain;
            model.IosUpdatedExplain = iosAppInfo.UpdatedExplain;
            model.AndroidSchemalUrl = androidAppInfo.SchemalUrl;
            model.IosSchemalUrl = iosAppInfo.SchemalUrl;

            return View(model);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Edit(AppInfoModel model)
        {
            if (model.Id > 0)
            {
                ViewBag.TableTitle = "應用修改";
                Th.PageHeaderCrumbs = new List<string> { "應用修改", "Home", "應用管理" };
            }
            else
            {
                ViewBag.TableTitle = "應用添加";
                Th.PageHeaderCrumbs = new List<string> { "應用添加", "Home", "應用管理" };
            }

            Th.PageHeaderMenus = new Dictionary<string, string> { { "應用列表", Url.Action("List") } };
            //移除這三個屬性的驗證
            ModelState.Remove("Id");
            ModelState.Remove("AndroidPushDate");
            ModelState.Remove("IosPushDate");
            if (!ModelState.IsValid)
            {
                ViewBag.HasModelError = true;
                return View(model);
            }

            var app = appService.GetModel(s => s.Id == model.Id && s.CreateUserId == userId);
            if (app != null)
            {
                //修改的話
                //首先之前的文件如果有新的上傳的話要刪除之前的文件                
                app.AppInfos = appInfoService.GetList(s => s.AppId == app.Id).ToList();
            }
            else
            {
                app = new App();
            }

            app.Identity = model.Identity;
            app.Name = model.Name;
            app.PassWord = model.PassWord;
            app.CreateUserId = userId;
            app.UpdateUserId = userId;

            var androidAppInfo = app.AndroidInfo;
            var iosAppInfo = app.IosInfo;


            androidAppInfo.Size = model.AndroidAppSize;
            iosAppInfo.Size = model.IosAppSize;
            androidAppInfo.PushDate = model.AndroidPushDate;
            iosAppInfo.PushDate = model.IosPushDate;
            androidAppInfo.Url = model.AndroidUrl;
            iosAppInfo.Url = model.IosUrl;
            androidAppInfo.Version = model.AndroidVersion;
            iosAppInfo.Version = model.IosVersion;
            androidAppInfo.Description = model.AndroidDescription;
            iosAppInfo.Description = model.IosDescription;
            androidAppInfo.UpdatedExplain = model.AndroidUpdatedExplain;
            iosAppInfo.UpdatedExplain = model.IosUpdatedExplain;
            androidAppInfo.CreateUserId = userId;
            iosAppInfo.CreateUserId = userId;
            androidAppInfo.UpdateUserId = userId;
            iosAppInfo.UpdateUserId = userId;
            androidAppInfo.SchemalUrl = model.AndroidSchemalUrl;
            iosAppInfo.SchemalUrl = model.IosSchemalUrl;

            //三個文件單獨獲取 AppLogo,AppLogoFile
            //規則是 input file以file結尾，hidden文件去掉file
            var source = new Dictionary<string, string>();
            string file1 = "AppLogo", file2 = "AndroidTestUrl", file3 = "IosTestUrl";
            source.Add(file1, ".jpg");
            source.Add(file2, "apk");
            source.Add(file3, "Pxl");

            var result = new Dictionary<string, string>();

            var path2 = "~/SaveFile/AppLogo/";
            var path = Server.MapPath("~/SaveFile/AppLogo/");
            foreach (var item in source.Keys)
            {
                var key = string.Concat(item, "File");
                var file = Request.Files[key];
                if (file != null && !string.IsNullOrEmpty(file.FileName))
                {
                    var ext = string.Empty;
                    ext = source[item];
                    if (!ext.StartsWith(".")) ext = "." + ext;

                    var fileName = model.Identity.GetFileName(ext);
                    var savePath = path + fileName;
                    Directory.CreateDirectory(path);
                    file.SaveAs(savePath);

                    //必須是保存相對路徑，這樣前台才能訪問
                    result.Add(item, path2 + fileName);
                }
            }

            if (result.ContainsKey(file1))
            {
                //刪除之前的文件
                FileHelper.Delete(app.AppLogo);
                app.AppLogo = result[file1];
                //自動生成的路徑默認不包含/
                var listUrl = Url.Action("List", "app", null, "http").ToLower();
                listUrl = listUrl.Replace("app/list", "");
                app.LogoUrl = listUrl + app.AppLogo.Replace("~", "");
            }
            if (result.ContainsKey(file2))
            {
                FileHelper.Delete(androidAppInfo.TestUrl);
                androidAppInfo.TestUrl = result[file2];
            }
            if (result.ContainsKey(file3))
            {
                FileHelper.Delete(iosAppInfo.TestUrl);
                iosAppInfo.TestUrl = result[file3];
            }


            var infos = new List<AppInfo> { androidAppInfo, iosAppInfo };
            try
            {
                var id = appService.AddOrUpdate(app, infos);
                if (id > 0)
                {
                    return RedirectToAction("List");
                }
                AddErrorInfo("操作失敗");
            }
            catch (Exception ex)
            {
                AddErrorInfo(ex.Message);
            }
            return View(model);
        }

        public ActionResult List()
        {
            ViewBag.TableTitle = "應用列表";
            Th.PageHeaderCrumbs = new List<string> { "應用列表", "Home", "應用管理" };
            Th.PageHeaderMenus = new Dictionary<string, string> { { "應用添加", Url.Action("Create") } };
            var appList = appService.GetList();

            var ids = appList.Select(s => s.Id);
            var infos = appInfoService.GetList(s => ids.Contains(s.AppId));

            foreach (var item in appList)
            {
                item.AppInfos = infos.Where(s => item.Id == s.AppId).ToList();
            }

            var columns = new List<string> { "前台預覽", "掃碼預覽", "名稱", "Logo", "密碼", "創建日期", "Android測試文件", "Ios測試文件", "操作" };
            ViewBag.Columns = columns;

            return View(appList);
        }

        /// <summary>
        ///     多选删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Delete(params int[] ids)
        {
            //如果有的話就
            if (ids == null || ids.Count() == 0)
            {
                return Json(new AjaxResult { status = false, msg = "請選擇一項" });
            }

            appService.DeleteList(userId, ids);
            return Json(new AjaxResult { msg = "操作成功", url = Url.Action("List") });
        }

        public ActionResult Delete(int? id)
        {
            //如果有的話就
            if (id == null)
            {
                return RedirectToAction("List");
            }

            appService.DeleteModel(userId, id.Value);
            return RedirectToAction("List");
        }

        public ActionResult Download(int? id)
        {
            var appInfo = appInfoService.GetModel(s => s.Id == id && s.CreateUserId == userId);
            var url = appInfo?.TestUrl;
            var serverPath = Server.MapPath(url);
            var filename = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();

            //文件不存在時，會拋出異常的
            if (System.IO.File.Exists(serverPath))
                return File(serverPath, "application/octet-stream", filename);
            return new EmptyResult();
        }

        public void QrCode(string url)
        {
            QrCodeHelper.Create(url);
        }
    }
}